import React, { useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom'
import axios from "axios";
import './App.css'
import { useState } from 'react';

const FaceRecognition = () => {
    let Navigate = useNavigate()
    //视频流存放
    const videoRef = useRef(null);
    const canvasRef = useRef(null);


    let [num, setnum] = useState(4)
    let color = ['blue', 'green', 'yellow', 'pink', 'purple', 'orange', 'white', 'gray']

    const [values, setvalues] = useState('red')

    // 捕获视频流
    useEffect(() => {
        let a = setInterval(() => {
            setvalues(color[Math.floor(Math.random() * color.length)])

        }, 1000)

        if (navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(stream => {
                    videoRef.current.srcObject = stream;
                    videoRef.current.play();
                })
                .catch(error => console.error("Error accessing media devices.", error));
        }

        setTimeout(() => {
            sendFrameToServer()
            clearInterval(a)
        }, 4000)

    }, []);



    // 发送视频帧到服务器
    const sendFrameToServer = async () => {
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');

        // 绘制当前视频帧到canvas
        context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);

        // 将canvas转换为图像数据URL
        const imageDataUrl = canvas.toDataURL('image/jpeg', 0.8); // 0.8 是压缩质量
        // console.log(imageDataUrl.split(',')[1])
        // 发送图像数据到服务器
        try {
            const response = await axios.post('/XXK/faceLogin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: imageDataUrl.split(',')[1]
            });
            if (response.data.code == 200) {
                videoRef.current.srcObject.getVideoTracks().forEach(track => {
                    track.stop()
                })
                videoRef.current.srcObject = null
                Navigate('/Dqj_home/XXK_home')
            } else {
                videoRef.current.srcObject.getVideoTracks().forEach(track => {
                    track.stop()
                })
                videoRef.current.srcObject = null
                Navigate('/Dqj_home/Dqj_homepage')
            }


            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const data = await response.json();
            console.log('Face recognition result:', data);
        } catch (error) {
            console.error('Error sending image to server:', error);
        }
    };

    return (
        <div className='renlian'
            style={{ backgroundColor: `${values}` }}
        >
            <video ref={videoRef} className='shexiang' />
            <canvas ref={canvasRef} style={{ display: 'none' }} />
            {/* <button onClick={sendFrameToServer}>Recognize Face</button> */}
        </div>
    );
};

export default FaceRecognition;